package me.flyray.bsin.server.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import me.flyray.bsin.context.BsinServiceContext;
import me.flyray.bsin.domain.entity.AgentCard;
import me.flyray.bsin.domain.enums.AIAgentType;
import me.flyray.bsin.exception.BusinessException;
import me.flyray.bsin.facade.service.AgentService;
import me.flyray.bsin.infrastructure.mapper.AgentCardMapper;
import me.flyray.bsin.mybatis.utils.Pagination;
import me.flyray.bsin.security.contex.LoginInfoContextHelper;
import me.flyray.bsin.security.domain.LoginUser;
import me.flyray.bsin.server.biz.AgentBiz;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shenyu.client.apache.dubbo.annotation.ShenyuDubboService;
import org.apache.shenyu.client.apidocs.annotations.ApiDoc;
import org.apache.shenyu.client.apidocs.annotations.ApiModule;
import org.apache.shenyu.client.dubbo.common.annotation.ShenyuDubboClient;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

import static me.flyray.bsin.constants.ResponseCode.*;

@Slf4j
@ShenyuDubboService(path = "/aiAgent", timeout = 6000)
@ApiModule(value = "aiAgent")
public class AgentServiceImpl implements AgentService {

    @Autowired
    private AgentCardMapper agentCardMapper;
    
    @Autowired
    private AgentBiz agentBiz;

    /**
     * 创建不同业务角色的数字分身
     * 一个业务角色对应一个身份智能体
     * @param requestMap
     */
    @ApiDoc(desc = "create")
    @ShenyuDubboClient("/create")
    @Override
    public AgentCard create(Map<String, Object> requestMap) {
        // 1. 参数解析和基础设置
        String agentType = MapUtils.getString(requestMap, "agentType");
        LoginUser loginUser = LoginInfoContextHelper.getLoginUser();
        AgentCard agentCard = agentBiz.buildAgentCardFromRequest(requestMap, loginUser);
        
        // 2. 根据ID查询是否存在，存在则更新
        if (StringUtils.isNotBlank(agentCard.getSerialNo())) {
            AgentCard existingAgent = agentCardMapper.selectById(agentCard.getSerialNo());
            if (existingAgent != null) {
                return agentBiz.updateExistingAgent(agentCard);
            }
        }
        
        // 3. 根据智能体类型处理创建逻辑
        return agentBiz.processAgentCreation(agentCard, agentType, loginUser);
    }
    

    @ApiDoc(desc = "edit")
    @ShenyuDubboClient("/edit")
    @Override
    public void edit(Map<String, Object> requestMap) {
        AgentCard agentCard = BsinServiceContext.getReqBodyDto(AgentCard.class, requestMap);
        if (agentCardMapper.updateById(agentCard) == 0){
            throw new BusinessException(ID_NOT_ISNULL);
        }
    }

    @ApiDoc(desc = "delete")
    @ShenyuDubboClient("/delete")
    @Override
    public void delete(Map<String, Object> requestMap) {
        String serialNo = MapUtils.getString(requestMap, "serialNo");
        if (agentCardMapper.deleteById(serialNo) == 0){
            throw new BusinessException(ID_NOT_ISNULL);
        }
    }

    @ApiDoc(desc = "getDetail")
    @ShenyuDubboClient("/getDetail")
    @Override
    public AgentCard getDetail(Map<String, Object> requestMap) {
        LoginUser loginUser = LoginInfoContextHelper.getLoginUser();
        
        // 优先从请求参数中获取查询条件
        String serialNo = StringUtils.defaultIfBlank(
            MapUtils.getString(requestMap, "serialNo"), 
            MapUtils.getString(requestMap, "agentId"));
        // 构建查询条件
        LambdaQueryWrapper<AgentCard> wrapper = new LambdaQueryWrapper<AgentCard>()
                .eq(AgentCard::getTenantId, loginUser.getTenantId())
                .eq(AgentCard::getSerialNo, serialNo);
        AgentCard agentCard = agentCardMapper.selectOne(wrapper);
        return agentCard;
    }

    @ApiDoc(desc = "getPageList")
    @ShenyuDubboClient("/getPageList")
    @Override
    public IPage<?> getPageList(Map<String, Object> requestMap) {
        LoginUser loginUser = LoginInfoContextHelper.getLoginUser();
        AgentCard agentCard = BsinServiceContext.getReqBodyDto(AgentCard.class, requestMap);
        Object paginationObj =  requestMap.get("pagination");
        Pagination pagination = new Pagination();
        BeanUtil.copyProperties(paginationObj,pagination);

        Page<AgentCard> page = new Page<>(pagination.getPageNum(),pagination.getPageSize());
        LambdaQueryWrapper<AgentCard> warapper = new LambdaQueryWrapper<>();
        warapper.orderByDesc(AgentCard::getCreateTime);
        warapper.eq(AgentCard::getTenantId, loginUser.getTenantId());
        warapper.eq(StringUtils.isNotBlank(agentCard.getAgentType()), AgentCard::getAgentType, agentCard.getAgentType());
        IPage<AgentCard> pageList = agentCardMapper.selectPage(page,warapper);
        return pageList;
    }

    @ApiDoc(desc = "getList")
    @ShenyuDubboClient("/getList")
    @Override
    public List<AgentCard> getList(Map<String, Object> requestMap) {
        String tenantId = (String) requestMap.get("tenantId");
        LambdaQueryWrapper<AgentCard> warapper = new LambdaQueryWrapper<>();
        warapper.eq(AgentCard::getTenantId, tenantId);
        List<AgentCard> agentCardList = agentCardMapper.selectList(warapper);
        return agentCardList;
    }

    /**
     * 一个业务角色对应一个DID身份智能体
     * 查询DID身份对应的智能体
     * 根据传参数和当前登录的用户信息查询
     * @param requestMap
     * @return
     */
    @ApiDoc(desc = "getDidAgent")
    @ShenyuDubboClient("/getDidAgent")
    @Override
    public AgentCard getDidAgent(Map<String, Object> requestMap) {
        LoginUser loginUser = LoginInfoContextHelper.getLoginUser();
        // 优先从请求参数中获取查询条件，如果没有提供则使用当前登录用户的信息

        // TODO 查询用户是否创建了DID身份

        String bizRoleTypeNo = StringUtils.defaultIfBlank(
            MapUtils.getString(requestMap, "bizRoleTypeNo"), loginUser.getBizRoleTypeNo());
        String bizRoleType = StringUtils.defaultIfBlank(
            MapUtils.getString(requestMap, "bizRoleType"), loginUser.getBizRoleType());
        // 构建查询条件
        LambdaQueryWrapper<AgentCard> wrapper = new LambdaQueryWrapper<AgentCard>()
                .eq(AgentCard::getTenantId, loginUser.getTenantId())
                .eq(AgentCard::getBizRoleType, bizRoleType)
                .eq(AgentCard::getBizRoleTypeNo, bizRoleTypeNo)
                .eq(AgentCard::getAgentType, AIAgentType.DID_APP_AGENT.getCode());
        AgentCard agentCard = agentCardMapper.selectOne(wrapper);
        return agentCard;
    }

    @ApiDoc(desc = "getSysAppAgent")
    @ShenyuDubboClient("/getSysAppAgent")
    @Override
    public AgentCard getSysAppAgent(Map<String, Object> requestMap) {
        LoginUser loginUser = LoginInfoContextHelper.getLoginUser();
        // 构建查询条件
        LambdaQueryWrapper<AgentCard> wrapper = new LambdaQueryWrapper<AgentCard>()
                .eq(AgentCard::getTenantId, loginUser.getTenantId())
                .eq(AgentCard::getAgentType, AIAgentType.SYS_APP_AGENT.getCode());
        AgentCard agentCard = agentCardMapper.selectOne(wrapper);
        if (agentCard == null) {
            throw new BusinessException(ID_NOT_ISNULL);
        }
        return agentCard;
    }



}
